<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        clearable
        size="mini"
        class="filter-item"
        style="width: 200px;"
        placeholder="请输入标题"
      />
      <!--      <el-select-->
      <!--        v-model="listQuery.type"-->
      <!--        clearable-->
      <!--        size="mini"-->
      <!--        style="width: 200px"-->
      <!--        class="filter-item"-->
      <!--        placeholder="请选择折扣类型"-->
      <!--      >-->
      <!--        <el-option-->
      <!--          v-for="type in typeOptions"-->
      <!--          :key="type.value"-->
      <!--          :label="type.label"-->
      <!--          :value="type.value"-->
      <!--        />-->
      <!--      </el-select>-->
      <el-select
        v-model="listQuery.status"
        clearable
        size="mini"
        style="width: 200px"
        class="filter-item"
        placeholder="请选择状态"
      >
        <el-option
          v-for="type in statusOptions"
          :key="type.value"
          :label="type.label"
          :value="type.value"
        />
      </el-select>
      <el-button
        v-permission="['GET /admin/coupon/list']"
        size="mini"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找
      </el-button>
      <el-button
        v-permission="['POST /admin/coupon/create']"
        size="mini"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加
      </el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >

      <el-table-column
        align="center"
        min-width="100px"
        label="活动编号"
        prop="id"
        sortable
      />

      <el-table-column
        align="center"
        min-width="100px"
        label="活动名称"
        prop="name"
      />
      <!--
      <el-table-column align="center" min-width="80px" label="介绍" prop="desc"/>

      <el-table-column align="center" min-width="100px" label="标签" prop="tag"/>
      -->
      <el-table-column
        v-show="dataForm.type===1"
        align="center"
        min-width="100px"
        label="最低消费"
        prop="min"
      >
        <template slot-scope="scope">满{{ scope.row.min }}元可用</template>
      </el-table-column>

      <el-table-column
        v-show="dataForm.type===1"
        align="center"
        min-width="100px"
        label="满减金额"
        prop="discount"
      >
        <template slot-scope="scope">满减{{ scope.row.reductionPrice }}元</template>
      </el-table-column>
      <el-table-column
        v-show="dataForm.type===2"
        align="center"
        min-width="100px"
        label="折扣比例"
        prop="discount"
      >
        <template slot-scope="scope">{{ scope.row.discountRate }}%</template>
      </el-table-column>
      <el-table-column
        v-show="dataForm.type===3"
        align="center"
        min-width="100px"
        label="特价"
        prop="discount"
      >
        <template slot-scope="scope">{{ scope.row.specialPrice }}元</template>
      </el-table-column>
      <el-table-column
        align="center"
        min-width="100px"
        label="商品使用范围"
        prop="goodsType"
      >
        <template slot-scope="scope">{{ scope.row.goodsType | formatGoodsType }}</template>
      </el-table-column>

      <el-table-column
        align="center"
        min-width="100px"
        label="活动类型"
        prop="type"
      >
        <template slot-scope="scope">{{ scope.row.type | formatType }}</template>
      </el-table-column>

      <el-table-column
        align="center"
        min-width="60px"
        label="状态"
        prop="status"
      >
        <template slot-scope="scope">{{ scope.row.status | formatStatus }}</template>
      </el-table-column>

      <el-table-column
        align="center"
        min-width="100px"
        label="活动开始时间"
        prop="status"
      >
        <template slot-scope="scope">{{ scope.row.startTime }}</template>
      </el-table-column>

      <el-table-column
        align="center"
        min-width="100px"
        label="活动结束时间"
        prop="status"
      >
        <template slot-scope="scope">{{ scope.row.endTime }}</template>
      </el-table-column>

      <el-table-column
        align="center"
        label="操作"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!--          <el-button-->
          <!--            v-permission="['GET /admin/coupon/read']"-->
          <!--            type="primary"-->
          <!--            size="mini"-->
          <!--            @click="handleDetail(scope.row)"-->
          <!--          >详情-->
          <!--          </el-button>-->
          <div class="button-container">
            <el-button
              v-permission="['POST /admin/coupon/update']"
              type="info"
              size="mini"
              @click="handleUpdate(scope.row)"
            >编辑
            </el-button>
            <el-button
              v-permission="['POST /admin/coupon/delete']"
              type="danger"
              size="mini"
              @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
        style="min-width: 80%;"
      >
        <el-form-item
          label="活动名称"
          prop="name"
        >
          <el-input v-model="dataForm.name" />
        </el-form-item>
        <el-form-item
          label="介绍"
          prop="desc"
        >
          <el-input v-model="dataForm.desc" />
        </el-form-item>
        <el-form-item
          label="标签"
          prop="tag"
        >
          <el-input v-model="dataForm.tag" />
        </el-form-item>
        <!--        <el-form-item-->
        <!--          label="活动类型"-->
        <!--          prop="type"-->
        <!--        >-->
        <!--          <el-select v-model="dataForm.type">-->
        <!--            <el-option-->
        <!--              v-for="type in typeOptions"-->
        <!--              :key="type.value"-->
        <!--              :label="type.label"-->
        <!--              :value="type.value"-->
        <!--            />-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <div v-show="dataForm.type===1">
          <el-form-item
            label="最低消费"
            prop="min"
          >
            <el-input v-model="dataForm.min">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item
            label="满减金额"
            prop="discount"
          >
            <el-input v-model="dataForm.discount">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </div>
        <div v-show="dataForm.type===2">
          <el-form-item
            label="折扣比例"
            prop="discountRate"
          >
            <el-input v-model="dataForm.discountRate">
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
        </div>
        <div v-show="dataForm.type===3">
          <el-form-item
            label="特价"
            prop="specialPrice"
          >
            <el-input v-model="dataForm.specialPrice">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </div>
        <el-form-item label="有效期时间">
          <el-col :span="11">
            <el-date-picker
              v-model="dataForm.startTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%;"
            />
          </el-col>
          <el-col
            :span="2"
            class="line"
          >至
          </el-col>
          <el-col :span="11">
            <el-date-picker
              v-model="dataForm.endTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%;"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="商品限制范围">
          <el-radio-group
            v-model="dataForm.goodsType"
            @change="chagneGoodsType"
          >
            <el-radio-button :label="0">全场通用</el-radio-button>
            <el-radio-button :label="1">指定分类</el-radio-button>
            <el-radio-button :label="2">指定商品</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-show="dataForm.goodsType === 1"
          label="所属分类"
        >
          <el-cascader
            v-model="dataForm.goodsValue"
            :props="props"
            :options="categoryList"
            expand-trigger="hover"
            @change="handleCategoryChange"
          />
        </el-form-item>
        <el-form-item
          v-show="dataForm.goodsType === 2"
          label="所属商品"
        >
          <el-select
            v-model="dataForm.goodsValue"
            v-el-select-loadmore="loadmore"
            multiple
            filterable
            clearable
            placeholder="请选择商品"
            style="width:60%"
            @clear="remove()"
            @change="selectProduct"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span>{{ item.name }}</span>
              <img
                :src="item.picUrl"
                style="height: 32px; float: right"
              >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          v-if="dialogStatus=='create'"
          type="primary"
          @click="createData"
        >确定
        </el-button>
        <el-button
          v-else
          type="primary"
          @click="updateData"
        >确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { listCatAndBrand, listGoods } from '@/api/business/goods'
import { createDiscount, deleteDiscount, listDiscount, updateDiscount } from '@/api/business/discount' // Secondary package based on el-pagination

const defaultTypeOptions = [
  {
    label: '满减活动',
    value: 1
  },
  {
    label: '折扣活动',
    value: 2
  },
  {
    label: '特价',
    value: 3
  },
  {
    label: '赠品',
    value: 4
  }
]

const defaultStatusOptions = [
  {
    label: '正常',
    value: 0
  },
  {
    label: '已过期',
    value: 1
  },
  {
    label: '已下架',
    value: 2
  }
]

export default {
  name: 'Coupon',
  components: { Pagination },
  directives: {
    'el-select-loadmore': {
      bind(el, binding) {
        const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')

        // 1. 保存原始监听函数
        const scrollHandler = function() {
          const condition = this.scrollHeight - this.scrollTop <= this.clientHeight
          if (condition) {
            binding.value()
          }
        }

        // 2. 将监听函数绑定到DOM元素
        SELECTWRAP_DOM.addEventListener('scroll', scrollHandler)

        // 3. 保存监听函数到元素属性
        el._select_loadmore_handler = scrollHandler
      },
      unbind(el) {
        const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')

        // 4. 使用保存的监听函数移除事件
        if (SELECTWRAP_DOM && el._select_loadmore_handler) {
          SELECTWRAP_DOM.removeEventListener('scroll', el._select_loadmore_handler)
        }
      }
    }
  },
  filters: {
    formatType(type) {
      for (let i = 0; i < defaultTypeOptions.length; i++) {
        if (type === defaultTypeOptions[i].value) {
          return defaultTypeOptions[i].label
        }
      }
      return ''
    },
    formatGoodsType(goodsType) {
      if (goodsType === 0) {
        return '全场通用'
      } else if (goodsType === 1) {
        return '指定分类'
      } else {
        return '指定商品'
      }
    },
    formatStatus(status) {
      if (status === 0) {
        return '正常'
      } else if (status === 1) {
        return '已过期'
      } else {
        return '已下架'
      }
    }
  },
  props: {
    disCountType: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      categoryList: [],
      typeOptions: Object.assign({}, defaultTypeOptions),
      statusOptions: Object.assign({}, defaultStatusOptions),
      list: undefined,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
        type: 4,
        status: undefined,
        sort: 'add_time',
        order: 'desc'
      },
      dataForm: {
        id: undefined,
        name: undefined,
        desc: undefined,
        tag: undefined,
        reductionPrice: 0,
        discountRate: 0,
        specialPrice: 0,
        min: 0,
        type: 4,
        status: 0,
        goodsType: 0,
        goodsValue: [],
        startTime: null,
        endTime: null,
        addTime: null,
        updateTime: null,
        deleted: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        name: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ]
      },
      downloadLoading: false,
      dialogVisible: false,
      options: [],
      formData: {
        page: 1,
        limit: 20,
        goodsId: null
      },
      props: { multiple: true, emitPath: false }
    }
  },
  created() {
    this.dataForm.type = this.disCountType
    this.listQuery.type = this.disCountType
    this.init()
    this.getList()
  },
  mounted() {
    this.getGoodList(this.formData)
  },
  methods: {
    chagneGoodsType() {
      this.dataForm.goodsValue = []
    },
    remove() {
      this.dataForm.goodsValue = []
    },
    loadmore() {
      this.formData.page++
      this.getGoodList(this.formData)
    },
    getGoodList(formData) {
      this.listLoading = true
      listGoods(formData)
        .then(response => {
          const _res = response.data.data.items
          this.options = [...this.options, ..._res]
          this.listLoading = false
        })
        .catch(() => {
          this.total = 0
          this.listLoading = false
        })
      // 这里是接口请求数据, 带分页条件
    },
    selectProduct(selVal) {
      this.dialogVisible = true
      this.listLoading = true
      console.log(selVal)
      this.dataForm.goodsValue = selVal
    },
    handleCategoryChange(value) {
      console.log(value)
      this.dataForm.goodsValue = value
      console.log(this.dataForm.goodsValue)
    },
    init: function() {
      listCatAndBrand().then(response => {
        this.categoryList = response.data.data.categoryList
      })
    },
    getList() {
      this.listLoading = true
      listDiscount(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        name: undefined,
        desc: undefined,
        tag: undefined,
        reductionPrice: 0,
        discountRate: 0,
        specialPrice: 0,
        min: 0,
        type: this.disCountType,
        status: 0,
        goodsType: 0,
        goodsValue: [],
        startTime: null,
        endTime: null,
        addTime: null,
        updateTime: null,
        deleted: 0
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createDiscount(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        if (this.dataForm.days === 0) {
          this.dataForm.daysType = 1
        } else {
          this.dataForm.daysType = 0
        }
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateDiscount(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteData(row)
        })
        .catch(() => {})
    },
    deleteData(row) {
      deleteDiscount(row)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '删除成功'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.data.errmsg
          })
        })
    },
    handleDetail(row) {
      this.$router.push({ path: '/promotion/couponDetail', query: { id: row.id }})
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          'ID',
          '名称',
          '内容',
          '标签',
          '最低消费',
          '减免金额',
          '每人限领',
          '数量'
        ]
        const filterVal = [
          'id',
          'name',
          'desc',
          'tag',
          'min',
          'discount',
          'limit',
          'total'
        ]
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '信息')
        this.downloadLoading = false
      })
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.button-container {
  display: flex;
  flex-wrap: wrap; /* 允许换行 */
  justify-content: flex-end; /* 左对齐 */
}
.button-container .el-button {
  margin-right: 10px; /* 按钮之间的间距 */
  margin-bottom: 10px; /* 换行时按钮之间的间距 */
}
.button-container .el-button:not(:first-child) {
  margin-left: 0; /* 最后一个按钮不需要右边距 */
}
</style>
